<template>
  <transition name="bounce">
    <div class="mui-content pd">
      <mh-header headName="支付"> </mh-header>
      <div class="total-pay mui-text-center">
        <p>
          <span class="label-price">￥</span>
          <span class="t-price">{{price}}</span>
        </p>
        <p class="sub-tit">费用</p>
      </div>
      <div class="account-balance">
        <p class="cur-balance mh-pd-lr">当前账户余额：￥{{money}}</p>
        <p class="choose-val mh-pd-lr" v-if='!balanceFlag'>账户余额不足，请先充值！</p>
        <p class="choose-val mh-pd-lr" v-if='!balanceFlag'>选择充值金额</p>
        <ul class="quick-list mh-pd-lr flex" v-if='!balanceFlag'>
          <li :class='curType==item.type ? "quick-charge mui-text-center quick-cur" : "quick-charge mui-text-center"' v-for="(item, index) in quickCharge" @click='getType(item.type, index)'>
            <a href="javascript:" v-text="`￥${item.value}`">￥-</a>
          </li>
        </ul>
        <p class="mh-pd-lr">支付金额: <span class="price">￥{{payPrice}}</span></p>
      </div>

      <div class="choose-payment">
        <p class="mh-pd">请选择支付账户</p>
        <ul>
          <li class="payment mh-pd-lr" @click='getPayType(1)'>
            <a href="javascript:">
              <img class="pay-icon" src="../../assets/images/ico/ic_alipay.png" alt="支付宝">
              <span>支付宝</span>
              <img v-if='payType==1' class="pay-check" src="../../assets/images/ico/icon-radio-check.png">
              <img v-if='payType==2' class="pay-check" src="../../assets/images/ico/icon-radio.png">
            </a>
          </li>
          <li class="payment mh-pd-lr" @click='getPayType(2)'>
            <a href="javascript:">
              <img class="pay-icon" src="../../assets/images/ico/ic_wechat.png" alt="微信支付">
              <span>微信</span>
              <img v-if='payType==2' class="pay-check" src="../../assets/images/ico/icon-radio-check.png">
              <img v-if='payType==1' class="pay-check" src="../../assets/images/ico/icon-radio.png">
            </a>
          </li>
        </ul>
      </div>

      <div class="mui-content-padded" v-if='!balanceFlag'>
        <button type="button" class="mui-btn-block mh-btn" @click='pay'>确定支付</button>
      </div>
      <div class="mui-content-padded" v-if='balanceFlag'>
        <button type="button" class="mui-btn-block mh-btn" @click='balancePay'>余额支付</button>
      </div>
    </div>
  </transition>
</template>

<script>
  import MhHeader from '@/components/mh-header/mh-header';
  import {MH_API} from "@/api/api";

  let payArr = null;
  //let ALIPAYSERVER = 'http://demo.dcloud.net.cn/helloh5/payment/alipay.php?total=';
  //let WXPAYSERVER = 'http://demo.dcloud.net.cn/helloh5/payment/wxpay.php?total=';
  let ALIPAYSERVER = MH_API.aliPay;
  let WXPAYSERVER = MH_API.wxPay;
  // let ALIPAYSERVER = 'http://demo.dcloud.net.cn/payment/?payid=alipay';
  // let WXPAYSERVER = 'http://demo.dcloud.net.cn/payment/?payid=wxpay';
  export default {
    name: "pay",
    data () {
      return {
        quickCharge: [
          {
            type: 1,
            value: 10
          },
          {
            type: 2,
            value: 20
          },
          {
            type: 3,
            value: 50
          },
          {
            type: 4,
            value: 100
          },
          {
            type: 5,
            value: 200
          }
        ],
        curType: 0,
        payType: 1,
        price: 0,
        payPrice: 0,
        money: 0,
        balanceFlag: false,
        orderId: null
      }
    },
    components: {
      MhHeader
    },
    methods:{
      getType(type, index){
        this.curType = type;
        this.payPrice = this.quickCharge[index].value;
      },
      getPayType(type){
        console.log(type)
        this.payType = type;
      },
      //余额支付
      balancePay(){
        let self = this;
        MH_API.balancePay({
          order_id: self.orderId
        }).then(res => {
          if (res.status === 200) {
            mui.toast("支付成功")
          }
        })
      },
      //支付
      pay(){
        if(this.curType==0){
          mui.toast("请选择充值金额");
          return false
        }
          // 从服务器请求支付订单  
          var PAYSERVER='';  
          let channel = null;
          let payType = this.payType;
          let self = this;
          if(payType==1){  
              PAYSERVER=ALIPAYSERVER;
              for(let i=0,len=payArr.length;i<len;i++){
                if(payArr[i].id=="alipay"){
                  channel = payArr[i];
                }
              }
              //channel = payArr[0];
          }else if(payType==2){  
              PAYSERVER=WXPAYSERVER;
              for(let i=0,len=payArr.length;i<len;i++){
                if(payArr[i].id=="wxpay"){
                  channel = payArr[i];
                }
              }
          }else{  
              plus.nativeUI.alert("不支持此支付通道！",null,"捐赠");  
              return;  
          }  
          var appid=plus.runtime.appid;
          if(navigator.userAgent.indexOf('StreamApp')>=0){
            appid='Stream';
          }
          //PAYSERVER+='&appid='+appid+'&total=';

          var xhr=new XMLHttpRequest(); //uni-app中请使用uni的request api联网  
          xhr.onreadystatechange=function(){  
              switch(xhr.readyState){  
                  case 4:  
                  if(xhr.status==200){ 
                    console.log(JSON.stringify(xhr))
                    console.log(xhr.responseText)
                      plus.payment.request(channel,xhr.responseText,function(result){  
                          plus.nativeUI.alert("支付成功！",function(){  
                              back();  
                          });  
                      },function(error){
                          console.log(JSON.stringify(error));
                          plus.nativeUI.alert("支付失败：" + error.code);  
                      });  
                  }else{  
                      mui.toast("获取订单信息失败！");  
                  }  
                  break;  
                  default:  
                  break;  
              }  
          }
          //xhr.open('GET',PAYSERVER + "0.01"); 
          xhr.open('POST',PAYSERVER + "&payment=0.01");  
          //xhr.open('GET',PAYSERVER + "&payment=" + self.payPrice);  
          xhr.setRequestHeader("Authorization", window.localStorage.getItem("token"));
          xhr.send();  
      }
    },
    created(){
      let price = this.$route.query.num;
      if(price){
        this.price = price;
        this.payPrice = price;
      }
      let orderId = this.$route.query.orderId;
      let orderPrice= this.$route.query.price;
      if(orderPrice){
        this.price = orderPrice;
        this.payPrice = orderPrice;
      }
      if(orderId){
        this.orderId = orderId;
      }
      let self = this;
      //余额
      MH_API.getBalance({}).then(res => {
        if (res.status === 200) {
          self.money = res.data.gold;
          let gold = parseFloat(res.data.gold);
          if(gold > 0 && gold > self.price){
            self.balanceFlag = true
          }
        }
      })
    },
    mounted () {
      mui.plusReady(function () {
        // 获取支付通道  
        plus.payment.getChannels(function(channels){
            console.log(JSON.stringify(channels))
            payArr = channels;
            //channel=channels[0];  
        },function(e){  
          console.log("获取支付通道失败："+e.message);  
        });

      })
    }
  }
</script>

<style lang="scss" scoped>
  html,body,.mh-app {background: #f2f2f2;}
  .total-pay {
    padding: 1rem 0;
    background: #fff;
    margin-bottom: 1rem;
  }
  .t-price {
    font-size: 3rem;
    color: #333;
  }
  .label-price {
    font-size: 1.3rem;
    color: #333;
  }
  .sub-tit {
    font-size: 1.5rem;
    color: #333;
  }
  .account-balance {
    padding-bottom: 1rem;
    margin-bottom: 1rem;
    background: #fff;
  }
  .cur-balance {
    padding-top: .5rem;
    padding-bottom: .5rem;
    border-bottom: 1px solid #eeeeee;
    color: #333;
    font-size: 1.4rem; margin-bottom:0.5rem;
  }
  .choose-val {
    padding-top: .5rem;
    padding-bottom: .5rem;
  }
  .quick-list {
    flex-flow:row wrap;
  }
  .quick-charge {
    display: inline-block;
    width: 31%;
    margin-right: 2.33%;
    margin-bottom: .5rem;
    font-size: 2.4rem;
    padding: 1.5rem 0;
    border: 1px solid #999; border-radius:2px;
    a {
      color: #999;
    }
  }
  .quick-cur{ border-color:#F3786D;}
  .quick-cur a{ color:#F3786D;}
  .choose-payment {
    background: #fff;
  }
  .payment {
    padding-top: 1rem;
    padding-bottom: 1rem;
    border-top: 1px solid #eeeeee;
    .pay-icon {
      width: 4rem;
    }
    .pay-check{ height:1.6rem; float:right; margin-top:1rem;}
  }
</style>
